/**
 * @author YinHang
 */
;(function () {
	window.Tower = function (image, sWidth, sHeight, attackRadius, aggressivity, delay, mode) {
		window.Tower.base.call(this, image, sWidth, sHeight);
		this.attackRadius = attackRadius;
		this.towerCenterX = this.x + this.width / 2;
		this.towerCenterY = this.y + this.height / 2;
		this.aggressivity = aggressivity;
		this.activation = false;
		this.fetching = false;
		this.startDegrees = 0;
		this.endDegrees = (Math.PI / 180) * 360;
		this.lastAttachTime = new Date().getTime();
		this.delay = 100;
		this.mode = mode || window.Tower.MODE_SIGHT;
		this.rotateAngle = 0;
	};
	
	Gamepackage.extend(window.Tower, Gamepackage.ui.g2d.Sprite);
	var Prototype = window.Tower.prototype;
	
	var Physics = Gamepackage.ui.g2d.physics.Physics;
	
	window.Tower.MODE_SIGHT = 0;
	window.Tower.MODE_AREA = 1;
	
	Prototype.sight = function (enemy) {
		if(this.activation)
		{
			var enemyCenterX = enemy.getX() + enemy.getWidth() / 2;
			var enemyCenterY = enemy.getY() + enemy.getHeight() / 2;
			if(Physics.Distance(enemyCenterX, enemyCenterY, this.towerCenterX, this.towerCenterY) <= this.attackRadius)
			{
				enemy.hurt(this.aggressivity);
				this.rotateAngle = Physics.Angle(this.towerCenterX, this.towerCenterY, enemyCenterX, enemyCenterY);
				return true;
			}
		}
		return false;
	};
	
	Prototype.sightAllEnemy = function (enemys) {
		for(var i=enemys.iterator();i.hasNext();)
		{
			if(this.sight(i.next()) && this.mode == window.Tower.MODE_SIGHT)
				break;
		}
	};
	
	Prototype.drawSuper = Prototype.draw;
	Prototype.setXSuper = Prototype.setX;
	Prototype.setYSuper = Prototype.setY;
	
	Prototype.setX = function (x) {
		this.setXSuper(x);
		this.towerCenterX = this.x + this.width / 2;
	};
	
	Prototype.setY = function (y) {
		this.setYSuper(y);
		this.towerCenterY = this.y + this.height / 2;
	};
	
	Prototype.draw = function (g) {
		g.context.save();
		g.context.translate(this.towerCenterX, this.towerCenterY);
		g.context.rotate(( Math.PI / 180 ) * this.rotateAngle);
		g.context.translate(this.towerCenterX * -1, this.towerCenterY * -1);
		if(this.fetching)
		{
			g.context.lineWidth = "2";
			g.drawArcs("#cccccc", this.towerCenterX, this.towerCenterY, this.attackRadius, this.startDegrees, this.endDegrees, true);
			g.fillArcs("rgba(255, 165, 0, 0.5)", this.towerCenterX, this.towerCenterY, this.attackRadius - 1, this.startDegrees, this.endDegrees, true);
			g.context.lineWidth = "1";
		}
		this.drawSuper(g);
		g.context.restore();
	};
	
	Prototype.clone = function () {
		return new window.Tower(this.image, this.sWidth, this.sHeight, this.attackRadius, this.aggressivity);
	};
	
	Prototype.fatch = function () {
		this.fetching = true;
	};
	
	Prototype.cancelFetch = function () {
		this.fetching = false;
	};
	
	Prototype.doActivation = function () {
		this.activation = true;
	};
	
})();
